module Magicloud.List where

import Data.List
import Prelude
import Data.Maybe

breakInto :: [a] -> Int -> [[a]]
breakInto [] _ = []
breakInto xs cnt =
  [a] ++ (breakInto b cnt)
  where
    (a, b) = splitAt cnt xs

splitByListA :: (Eq a) => [a] -> [a] -> [[a]]
splitByListA tok ys =           -- buggy
  let s = foldr1 (\a b ->
                      filter (\c ->
                                elem (c + 1) b
                             ) a
                   ) $ map (\x ->
                              elemIndices x ys
                           ) tok in
  filter (not . null) $ map (\(a, b) ->
                              drop a $ take b ys
                            ) $ foldl (\a b ->
                                        a ++ [((snd $ last a) + (length tok), b)]
                                      ) [(0, head s)] ((tail s) ++ [length ys])

splitByListB :: (Eq a) => [a] -> [a] -> [[a]]
splitByListB tok ys =
  let tmp = filter (isPrefixOf tok) $ tails ys in
  filter (not . null) $ map (drop $ length tok) $ zipWith (\a b ->
                                                         take (length a - length b) a
                                                       ) ((tok ++ ys) : tmp) $ tmp ++ [[]]
padL :: Int -> [a] -> [a] -> [a]
padL l tok ys =
  (take (l - (length ys)) $ cycle tok) ++ ys

filterMaybe :: (a -> Maybe b) -> [a] -> [b]
filterMaybe f = map fromJust . filter (\mb ->
                                        case mb of
                                          Nothing -> False
                                          _ -> True
                                      ) . map f

filterMaybeM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
filterMaybeM _ [] = return []
filterMaybeM f (x : xs) = do
  flg <- f x
  ys <- filterMaybeM f xs
  return $ case flg of
    Nothing -> ys
    Just x_ -> x_ : ys